package com.eet.juc.lock;

import java.util.concurrent.*;

/**
 * 多线程买票问题
 *
 * @author zheng.zhang
 */
public class TicketDemo {
    /**
     * 线程池四种创建
     */
    private final static ExecutorService EXECUTOR_SERVICE = Executors.newFixedThreadPool(5);

    /**
     * 阿里巴巴编码规范推荐手动创建线程池,让我们更加明确线程池的运行规则,规避资源耗尽的风险
     */
    private final static ThreadPoolExecutor EXECUTOR = new ThreadPoolExecutor(3, 5, 1L,
            TimeUnit.SECONDS,
            new LinkedBlockingDeque<>(3),
            Executors.defaultThreadFactory(),
            new ThreadPoolExecutor.AbortPolicy()
    );

    public static void main(String[] args) {
        Ticket ticket = new Ticket();
        EXECUTOR.submit(() -> {
            for (int i = 0; i < 40; i++) {
                ticket.sale();
            }
        });

        EXECUTOR_SERVICE.submit(() -> {
            for (int i = 0; i < 40; i++) {
                ticket.sale();
            }
        });

        EXECUTOR.submit(() -> {
            for (int i = 0; i < 40; i++) {
                ticket.sale();
            }
        });
    }
}

class Ticket {
    private int number = 100;

    public synchronized void sale() {
        if (number > 0) {
            System.out.println(Thread.currentThread().getName() + "卖出了第" + (number--) + "张票, 剩余" + number + "张票!");
        }
    }
}
